const express = require("express");
const { type } = require("os");

const pool = require("../pool");

const router = express.Router();

// 获取车辆展区品牌
router.get("/s/recommendcar", (req, res) => {
  let brands = req.query.brands;
  pool.query(
    "select *from brand where bname in(?)",
    [brands],
    (err, result) => {
      if (err) throw err;
      res.send(result);
    }
  );
});

// 获取首页展望车辆信息表
router.get("/s/carboothlist", (req, res) => {
  pool.query(
    "select bid,cartitle,car_price,guide_price,isNewEnergy,stay_long_act,limit_act,show_pic from car_basic where is_demo_booth = ?",
    [1],
    (err, result) => {
      if (err) throw err;
      res.send(result);
    }
  );
});

// 获取待上线汽车表
router.get("/s/onthenew", (req, res) => {
  pool.query("select * from on_the_new", (err, result) => {
    if (err) throw err;
    res.send(result);
  });
});

// 获取首页汽车展示列表
router.get("/s/cars", (req, res) => {
  let page = req.query.page;
  let carList = {};
  pool.query(
    `select bid,cars,cartitle,car_price,guide_price,isNewEnergy,show_pic from car_basic limit ?,8`,
    [(page - 1) * 8],
    (err, result) => {
      if (err) throw err;
      carList.cars = result;
      pool.query("select count(bid) from car_basic", (err, result2) => {
        carList.allPage = Math.ceil(result2[0]["count(bid)"] / 8);
        carList.page = parseInt(page);
        res.send(carList);
        // console.log(carList)
      });
      // console.log(result)
    }
  );
});

// 获取车辆品牌表
router.get("/s/brands", (req, res) => {
  pool.query("select * from brand", (err, result) => {
    if (err) throw err;
    res.send(result);
  });
});

// 获取筛选出来的车辆信息
router.get("/s/selectcar", (req, res) => {
  let obj = req.query;
  let blist = obj.blist;
  let mlist = obj.mlist;
  let sprice = obj.sprice;
  let skey = obj.skey;
  let srank = obj.srank;
  let sql = "";
  let arr = [];
  let allres = {};
  let page = obj.page;
  if (srank == "def") {
    srank = " order by bid";
  } else if (srank == "asc") {
    srank = " order by car_price asc";
  } else {
    srank = " order by car_price desc";
  }
  if (sprice) {
    arr.push(parseInt(sprice[0]));
    arr.push(parseInt(sprice[1]));
  }
  mlist && arr.push(mlist);
  skey && arr.push(`%${skey}%`);

  // console.log(srank);
  if (blist) {
    pool.query(
      "select bdid from brand where bname in(?)",
      [blist],
      (err, result) => {
        if (err) throw err;
        let bid = [];
        result.forEach((item) => {
          bid.push(item.bdid);
        });
        arr.push(bid);
        // console.log("arr", arr);
        sql = `select  bid,cartitle,cars,car_price,guide_price,show_pic,is_self,isNewEnergy from car_basic${
          sprice || mlist || blist || skey ? " where" : "".trim()
        }${sprice ? " (car_price between ? and ?)" : "".trim()}${
          mlist && sprice ? " and" : "".trim()
        }${mlist ? " (car_models in(?))" : "".trim()}${
          skey && (mlist || sprice) ? " and" : ""
        }${skey ? " (concat(cars,cartitle,car_models) like ?)" : ""}${
          sprice || mlist || skey ? " and" : "".trim()
        }${" brand_id in(?)"}${srank} limit ${(page - 1) * 12},12`;
        // console.log(sql);
        pool.query(sql, arr, (err, result1) => {
          if (err) throw err;
          allres.cars = result1;
          sql = `select  count(bid) from car_basic${
            sprice || mlist || blist || skey ? " where" : "".trim()
          }${sprice ? " (car_price between ? and ?)" : "".trim()}${
            mlist && sprice ? " and" : "".trim()
          }${mlist ? " (car_models in(?))" : "".trim()}${
            skey && (mlist || sprice) ? " and" : ""
          }${skey ? " (concat(cars,cartitle,car_models) like ?)" : ""}${
            sprice || mlist || skey ? " and" : "".trim()
          }${" brand_id in(?)"}`;
          // console.log(sql);
          pool.query(sql, arr, (err, result2) => {
            if (err) throw err;
            allres.carsCount = result2[0]["count(bid)"];
            allres.allPage = Math.ceil(result2[0]["count(bid)"] / 12);
            res.send(allres);
          });
        });
      }
    );
  } else {
    sql = `select bid,cartitle,cars,car_price,guide_price,show_pic,is_self,isNewEnergy from car_basic${
      sprice || mlist || blist || skey ? " where" : "".trim()
    }${sprice ? " (car_price between ? and ?)" : "".trim()}${
      mlist && sprice ? " and" : "".trim()
    }${mlist ? " (car_models in(?))" : "".trim()}${
      skey && (mlist || sprice) ? " and" : ""
    }${
      skey ? " (concat(cars,cartitle,car_models) like ?)" : ""
    }${srank} limit ${(page - 1) * 12},12`;
    // console.log(sql);
    pool.query(sql, arr, (err, result) => {
      if (err) throw err;
      allres.cars = result;
      sql = `select count(bid) from car_basic${
        sprice || mlist || blist || skey ? " where" : "".trim()
      }${sprice ? " (car_price between ? and ?)" : "".trim()}${
        mlist && sprice ? " and" : "".trim()
      }${mlist ? " (car_models in(?))" : "".trim()}${
        skey && (mlist || sprice) ? " and" : ""
      }${skey ? " (concat(cars,cartitle,car_models) like ?)" : ""}`;
      // console.log(sql);
      pool.query(sql, arr, (err, result1) => {
        if (err) throw err;
        // console.log(result1)
        allres.allCount = result1[0]["count(bid)"];
        allres.allPage = Math.ceil(result1[0]["count(bid)"] / 12);
        res.send(allres);
      });
    });
  }
});

// 获取所有车辆的大概信息用于搜索
router.get("/s/probably", (req, res) => {
  let arr = [];
  pool.query("select bid,show_pic,cartitle from car_basic", (err, result) => {
    if (err) throw err;
    arr.push(result);
    pool.query("select bdid,bname,b_value from brand", (err, result1) => {
      if (err) throw err;
      arr.push(result1);
      res.send(arr);
    });
  });
});

// 获取活动界面的汽车列表
router.get("/s/refresh", (req, res) => {
  let bidList = [];
  let type = `"${req.query.type}"`;
  let opt = req.query.opt;
  pool.query(
    `select bid,cartitle,car_price,guide_price,car_models,stamps,show_Pic from car_basic where ${opt} = ${type}`,
    (err, result) => {
      if (err) throw err;
      bidList = result.map((item) => item.bid);
      pool.query(
        "select car_id,basic_parp,motor from car_details where car_id in(?)",
        [bidList],
        (err, results) => {
          if (err) throw err;
          results.forEach((item) => {
            item.basic_parp = JSON.parse(item.basic_parp);
            item.motor = JSON.parse(item.motor);
          });
          result.forEach((item) => {
            item.stamps = JSON.parse(item.stamps);
            results.forEach((i) => {
              if (item.bid == i.car_id) {
                item.power = i.basic_parp.list[9].value;
                item.conp = i.motor.list[12].value;
              }
            });
          });
          //  results[0].basic_parp = JSON.parse(results[0].basic_parp)
          //  results[0].motor = JSON.parse(results[0].motor)
          res.send(result);
        }
      );
    }
  );
});

// 获取汽车详情信息
router.get("/s/detail", (req, res) => {
  let bid = req.query.bid;
  let results = [];
  console.log(bid);
  pool.query("select * from car_basic where bid = ?", [bid], (err, result) => {
    results.push(result[0]);
    pool.query("select * from car_pic where cid = ?", [bid], (err, result1) => {
      // console.log(result1[0].seat);
      result1[0].appearance = JSON.parse(result1[0].appearance);
      result1[0].central  = JSON.parse(result1[0].central);
      result1[0].seat  = JSON.parse(result1[0].seat);
      results.push(result1[0]);
      res.send(results);
    });
  });
});

module.exports = router;
